/* eslint-disable consistent-return */

import React, { Component } from 'react';
import { UploadOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Modal, Input, Upload, Button, message, Select, Spin } from 'antd';
import NsCustomer from '../../components/NsCustomer';
import Supplier from '../../components/NsSupplier';
import TableForm from './TableForm';
import { isRepeat, requestHeadersMd5 } from '@/utils/utils';

const FormItem = Form.Item;
const { Option } = Select;

class AddEditModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      uploadUrl: '/nsApi/fileServer/uploadFile',
      downloadUrl: '/nsApi/fileServer/downloadFile',
      affixList: props.dataInfo.fileListFormat || [],
    };
  }

  // 获取供应商名称
  getSuppName = value => {
    const { getSuppName, form } = this.props;
    getSuppName(value);
    form.resetFields(['areaList']);
    this.child.reSetPd();
  };

  // 获取地区
  selectArea = value => {
    const areaList = [];
    value.forEach(item => {
      areaList.push(item.key);
    });
    const { selectArea } = this.props;
    selectArea(areaList);
    this.child.reSetPd();
  };

  // 文件限制大小
  beforeUpload = () => {};

  // 文件上传
  changeUpload = info => {
    const { file, fileList } = info;
    const { downloadUrl, affixList } = this.state;
    const newData = affixList.map(item => ({ ...item }));
    if (file.status === 'done' && file.response.success) {
      const fileId = file.response.data.split('|')[0];
      const fileName = file.response.data.split('|')[1];
      fileList.forEach(f => {
        const temp = f;
        if (String(f.uid) === String(file.uid)) {
          temp.url = `${downloadUrl}?fileId=${fileId}&fileName=${fileName}`;
          temp.linkProps = { download: `${fileName}` };
        }
      });
      newData.push({
        uid: file.fileId,
        fileId,
        fileName,
      });
      this.setState({ affixList: newData });
      message.success('文件上传成功！');
    } else if (file.status === 'removed') {
      const newFileList = fileList.map(item => ({
        ...item,
        fileId: item.uid,
        fileName: item.name,
      }));
      this.setState({ affixList: newFileList });
    }
    if (file.status === 'error') {
      message.error('上传失败！');
    }
  };

  // 提交数据
  submitData = () => {
    const { modalData, dataInfo, form, productList, submitData } = this.props;
    const { affixList } = this.state;
    form.validateFields((err, values) => {
      const temp = values;
      if (!err) {
        if (!temp.custId) {
          temp.custId = '';
        }
        const areaList = [];
        const newDetList = [];
        Object.keys(temp.detList).forEach(i => {
          newDetList.push(temp.detList[i]);
        });

        temp.detList = newDetList;
        if (!temp.detList || !temp.detList.length) {
          return message.warning('请新增至少一条产品！');
        }
        if (isRepeat(temp.detList, 'pdId')) {
          message.warning('所选产品重复，请重新选择！');
          return;
        }
        affixList.forEach(item => {
          const temp1 = item;
          if (temp1.name) {
            temp1.fileId = temp1.fileId || temp1.uid;
            temp1.fileName = temp1.fileName || temp1.name;
            delete temp1.url;
            delete temp1.name;
            delete temp1.linkProps;
          }
          delete temp1.uid;
        });
        temp.areaList.forEach(item => {
          areaList.push({
            areaId: item.key,
            areaName: item.label,
          });
        });
        temp.detList.forEach(item => {
          const tem = item;
          productList.forEach(p => {
            if (String(item.pdId) === String(p.pdId)) {
              tem.chargFre = p.billFreq;
            }
          });
          if (tem.pdId.length > 1) {
            tem.flag = 1;
          } else {
            tem.flag = 0;
          }
        });
        temp.areaList = areaList;
        temp.affixList = affixList;

        temp.packList = temp.detList;

        temp.packList.forEach(items => {
          const temp2 = items;
          temp2.detList = [];
          temp2.pdId.forEach(pditem => {
            temp2.detList.push({
              pdId: pditem,
              fee: temp2.fee,
              chargFre: temp2.chargFre,
            });
          });
          delete temp2.fee;
          delete temp2.flag;
          delete temp2.pdId;
          delete temp2.chargFre;
        });
        delete temp.detList;
        const [arr1] = temp.recvSuppId.split('&');
        temp.recvSuppId = arr1;
        if (dataInfo.suppProtId) {
          modalData.forEach((paItem, paIndex) => {
            paItem.detList.forEach((deItem, deIndex) => {
              if (!deItem.isId) {
                if (
                  paItem.detList.some(
                    pitem =>
                      pitem.pdName ===
                      (temp.packList &&
                        temp.packList[paIndex] &&
                        temp.packList[paIndex].detList &&
                        temp.packList[paIndex].detList[deIndex] &&
                        temp.packList[paIndex].detList[deIndex].pdId)
                  )
                ) {
                  temp.packList[paIndex].detList[deIndex].pdId = deItem.pdId;
                }
              }
            });
          });
        }
        submitData(temp);
      }
    });
  };

  render() {
    const {
      modalVisible,
      handleModalVisible,
      dataInfo,
      productList,
      areaList,
      form: { getFieldDecorator },
      confirmLoading,
      areaLoading,
      form,
    } = this.props;
    const { uploadUrl, affixList } = this.state;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
    };
    const formItemLayouts = {
      labelCol: { span: 5 },
      wrapperCol: { span: 14 },
    };

    // 下拉列表
    // 文件上传部分
    const uploadProps = {
      beforeUpload: info => this.beforeUpload(info),
      action: uploadUrl,
      headers: requestHeadersMd5(),
      onChange: info => this.changeUpload(info, affixList),
    };
    // 文件列表格式化
    const uploadFileFormat = e => {
      if (Array.isArray(e)) {
        return e;
      }
      return e && e.fileList;
    };

    return (
      <div>
        <Modal
          width={700}
          title={dataInfo.suppProtName ? '修改' : '添加'}
          visible={modalVisible}
          okText="确定"
          cancelText="取消"
          onOk={this.submitData}
          onCancel={() => handleModalVisible(false)}
          destroyOnClose
          confirmLoading={confirmLoading}
        >
          <Form layout="horizontal">
            <FormItem {...formItemLayout} label="协议名称">
              {getFieldDecorator('suppProtName', {
                rules: [{ required: true, message: '请输入不超过100字符', max: 100 }],
                initialValue: dataInfo.suppProtName || undefined,
              })(<Input placeholder="请输入" />)}
            </FormItem>
            <FormItem {...formItemLayout} label="客户名称">
              {getFieldDecorator('custId', {
                initialValue: dataInfo.custId || undefined,
              })(<NsCustomer allowClear />)}
            </FormItem>
            <FormItem {...formItemLayout} label="供应商">
              {getFieldDecorator('recvSuppId', {
                rules: [{ required: true, message: '请选择' }],
                initialValue: dataInfo.recvSuppId || undefined,
              })(
                <Supplier allowClear onChange={this.getSuppName} disabled={!!dataInfo.recvSuppId} />
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="执行地区">
              {getFieldDecorator('areaList', {
                rules: [{ required: true, message: '请选择' }],
                initialValue: dataInfo.areaListFormat || undefined,
              })(
                <Select
                  placeholder="请选择"
                  mode="multiple"
                  labelInValue
                  showSearch
                  optionFilterProp="children"
                  onChange={this.selectArea}
                  notFoundContent={areaLoading ? <Spin size="small" /> : null}
                >
                  {areaList.map(item => (
                    <Option key={item.areaId}>{item.areaName}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
            <TableForm
              form={form}
              productList={productList}
              detList={dataInfo.packList || []}
              onRef={ref => {
                this.child = ref;
              }}
            />
            <FormItem {...formItemLayouts} label="附件">
              {getFieldDecorator('affixList', {
                rules: [{ required: false, message: '请上传附件' }],
                valuePropName: 'fileList',
                getValueFromEvent: uploadFileFormat,
                initialValue: dataInfo.fileListFormat || undefined,
              })(
                <Upload {...uploadProps} beforeUpload={this.beforeUpload}>
                  <Button icon={<UploadOutlined />}>上传附件</Button>
                </Upload>
              )}
            </FormItem>
          </Form>
        </Modal>
      </div>
    );
  }
}

export default Form.create()(AddEditModal);
